#include "main.h"

/*全局变量*/
char mobilebuf[size];//移动端和服务端通信的字符串
char validdata[7];//有效的7个字节数据
MSG msg;
INFO info;
pthread_mutex_t mutex;
char mob_str[4][20];//用于存储切割后的命令字符串

sqlite3* pdb;
char sql[size],*errmsg;
char** result;
int row,col;


int main(void)
{
	int fd,newfd;
	int ret;
	pthread_t tid1,tid2;//子线程号

	/*初始化互斥锁*/
	pthread_mutex_init(&mutex, NULL);

	/*创建子线程——接收协调器数据*/
	pthread_create(&tid1, NULL, coord_thread, NULL);	

	/*创建数据库和表*/
	//创建用户数据库
	sqlite3_open("user.db",&pdb);

	//创建用户表
	strncpy(sql,"create table if not exists users (username char[20] primary key,password char[50]);",size);
	sqlite3_exec(pdb, sql, NULL, NULL, &errmsg);

	/*添加初始用户*/
	strncpy(sql,"insert into users values('root','123');",size);
	sqlite3_exec(pdb, sql, NULL, NULL, &errmsg);
	strncpy(sql,"insert into users values('robin','123');",size);
	sqlite3_exec(pdb, sql, NULL, NULL, &errmsg);

	/*买卡、绑卡、监听*/	
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) 
	{
		perror("socket");
		exit(1);
	}
	//重用端口号
	int on = 1;
	setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); 

	struct sockaddr_in server;
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr("192.168.104.127");
	server.sin_port = htons(12001);
	ret = bind(fd, (struct sockaddr *)&server, sizeof(server));
	if (ret == -1) 
	{
		perror("bind");
		exit(1);
	}

	listen(fd, 100); //不阻塞，最多接听100个
	printf("Server have started!\n");
	
	struct sockaddr_in client;//保存客户端的socket地址
	socklen_t len = sizeof(client);

	while(1)//并发服务器须保证while里除了accept外不阻塞
	{
		/*接听*/
		newfd = accept(fd, (struct sockaddr *)&client, &len);
		if (newfd == -1)
		{
			perror("accept");
			exit(1);
		}

		printf("Connect success with client!\n");
		printf("---------------------------------\n");
		printf("ip\t%s\n", inet_ntoa(client.sin_addr));
		printf("port\t%d\n", ntohs(client.sin_port));
		printf("---------------------------------\n");

		/*创建子线程——和移动端交流*/
		pthread_create(&tid2, NULL, mob_thread, &newfd);
	}

	/*注销卡*/
	close(fd);

	/*关闭数据库*/
	sqlite3_close(pdb);

	return 0;
}

